package implementations.dm_kernel;

import interfaces.kernel.JCL_connector;
import interfaces.kernel.JCL_message;
import interfaces.kernel.JCL_message_control;
import interfaces.kernel.JCL_message_result;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ConnectorImpl implements JCL_connector{
	
	private Socket s; 
	private ObjectOutputStream out;
	private ObjectInputStream in;
	
	public ConnectorImpl(){
		super();
	}
	
	@Override
	public void connect(String host, int port) {
		// TODO Auto-generated method stub
		try {
			s = new Socket(host, port);			
		} catch (Exception e) {
			System.err.println("problem in connect method " + host);
		} 
	}

	@Override
	public JCL_message_result sendReceive(JCL_message msg) {
		// TODO Auto-generated method stub
		JCL_message_result fromServer;
		try {
			out = new ObjectOutputStream(s.getOutputStream());
			
			out.writeObject(msg);
			out.flush();
			
			in = new ObjectInputStream(s.getInputStream());
			fromServer = (JCL_message_result)in.readObject();	
								
			return fromServer;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("error in sendreceive method");
			return null;
		}
		
	}
	
	@Override
	public JCL_message_control sendReceive(JCL_message_control msg) {
		// TODO Auto-generated method stub
		JCL_message_control fromServer;
		try {
			out = new ObjectOutputStream(s.getOutputStream());
			out.writeObject(msg);
			out.flush();
			
			in = new ObjectInputStream(s.getInputStream());
			fromServer = (JCL_message_control)in.readObject();	
			
											
			return fromServer;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("error in sendreceive method");
			return null;
		}
		
	}

	@Override
	public boolean disconnect() {
		try{
			in.close();
		
			out.flush();
			out.close();
			
			s.close();
			
			return true;
		}catch (Exception e){
			System.err.println("problem in disconnect method");
			return false;
		}
	}
	


}
